<template>
   <div class="app-container">
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
         <el-form-item label="名称" prop="keyword">
            <el-input v-model="queryParams.keyword" placeholder="请输入名称" clearable style="width: 200px"
               @keyup.enter="handleQuery" />
         </el-form-item>
         <el-form-item label="版本" prop="version">
            <el-input v-model="queryParams.version" placeholder="请输入版本" clearable style="width: 200px"
               @keyup.enter="handleQuery" />
         </el-form-item>
         <el-form-item label="任务状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="任务状态" clearable style="width: 200px">
               <el-option label="启用" :value="1" />
               <el-option label="禁用" :value="0" />
            </el-select>
         </el-form-item>
         <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
         </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
         <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
         </el-col>
         <el-col :span="1.5">
            <el-button type="primary" plain icon="Delete" @click="handleDeleteBatch">删除</el-button>
         </el-col>
         <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="dataList" row-key="id" @selection-change="handleSelectionChange">
         <el-table-column type="selection" :selectable="selectable" width="55" />
         <el-table-column prop="name" label="名称" show-overflow-tooltip></el-table-column>
         <el-table-column prop="version" label="版本"></el-table-column>
         <el-table-column prop="fileUrl" label="文件地址"></el-table-column>
         <el-table-column prop="status" label="状态" width="80">
            <template #default="scope">
               <span v-if="scope.row.status === 1" >启用</span>
               <span v-else-if="scope.row.status === 0" >停用</span>
               <span v-else>-</span>
            </template>
         </el-table-column>
         <el-table-column label="操作" width="280" fixed="right" class-name="small-padding fixed-width">
            <template #default="scope">
               <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
               <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
               <template v-if="scope.row.status === 0">
                  <el-button link type="success" icon="Check" @click="handleEnable(scope.row.id)">启用</el-button>
               </template>
            </template>
         </el-table-column>
      </el-table>
      <pagination
         v-show="total > 0"
         :total="total"
         v-model:page="queryParams.pageNum"
         v-model:limit="queryParams.pageSize"
         @pagination="getList"
      />
      <!-- 添加或修改 -->
      <el-dialog :title="title" v-model="open" width="680px" append-to-body>
         <el-form ref="editRef" :model="form" :rules="rules">
            <el-row :gutter="10">
               <el-col :span="12">
                  <el-form-item label="名称" prop="type">
                     <el-input v-model="form.name" placeholder="请输入名称" clearable/>
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="版本" prop="type">
                     <el-input v-model="form.version" placeholder="请输入版本" clearable/>
                  </el-form-item>
               </el-col>
            </el-row>
            <el-row>
               <el-upload
                  v-loading="uploading"
                  :on-change="importFile"
                  :limit="1"
                  :show-file-list="false"
                  :auto-upload="false"
                  ref="fileUpload"
               >
                  <el-button type="primary">文件上传</el-button>
               </el-upload>
            </el-row>
            <el-row v-if="form.fileUrl">
               <el-form-item label="文件路径" prop="fileUrl">
                  {{ form.fileUrl || '' }}
               </el-form-item>
            </el-row>
         </el-form>
         <template #footer>
            <div class="dialog-footer">
               <el-button type="primary" @click="submitForm">确 定</el-button>
               <el-button @click="cancel">取 消</el-button>
            </div>
         </template>
      </el-dialog>
   </div>
</template>

<script setup name="Menu">
import { ref, watch, defineProps } from "vue";
import {
   dataDecodeUpdate,
   dataDecodeAdd,
   dataDecodeGetListByPage,
   dataDecodeGetDetail,
   dataDecodeDelete,
} from "@/api/dataDecode";
import { pullGetList } from "@/api/pull";
import { getToken } from "@/utils/auth";
import axios from "axios";

const { proxy } = getCurrentInstance();
const dataList = ref([]);
const open = ref(false);
const loading = ref(false);
const showSearch = ref(true);
const title = ref("");
const total = ref(0);

const data = reactive({
   form: {
      dataSystemId: null,
      fileUrl: null,
      id: null,
      name: null,
      version: null
   },
   queryParams: {
      pageNum: 1,
      pageSize: 10,
      status: null,
      keyword: null,
      version: null
   },
   detail: {},
   rules: {
      name: [{ required: true, message: "请输入名称", trigger: "change" }],
      version: [{ required: true, message: "请输入版本", trigger: "change" }],
   }
});

const { queryParams, form, detail, rules } = toRefs(data);

const props = defineProps({
   visible: {
      type: Number,
      default: null
   },
   id: {
      type: Number,
      default: null
   },
   systemId: {
      type: Number,
      default: null
   }
})
watch(() => props.visible, (newValue) => {
   if(newValue){
      getList();
   } else {
      queryParams.value = {
         pageNum: 1,
         pageSize: 10
      }
      dataList.value = []
      total.value = 0
      loading.value = false;
   }
},{ immediate:true })

/** 查询系统列表 */
function getList() {
   loading.value = true;
   dataDecodeGetListByPage(queryParams.value).then(response => {
      dataList.value = response.data.records;
      total.value = response.data.total;
      loading.value = false;
   }).catch(()=> loading.value = false);
}

/** 取消按钮 */
function cancel() {
   open.value = false;
   reset();
}

/** 表单重置 */
function reset() {
   form.value = {
      dataSystemId: null,
      fileUrl: null,
      id: null,
      name: null,
      version: null
   };
   proxy.resetForm("editRef");
   detail.value = {};
   editTargetId.value = null;
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd() {
   reset();
   open.value = true;
   title.value = "新增解析包";
}

const editTargetId = ref(null)
/** 修改按钮操作 */
async function handleUpdate(row) {
   reset();
   editTargetId.value = row.id
   dataDecodeGetDetail({id: row.id}).then(response => {
      form.value = {
         ...response.data
      };
      open.value = true;
      title.value = "修改解析包";
      getdataDecodePullOption(null)
   });
}

// 启用禁用
function handleEnable(id, status) {
   dataDecodeEnable({id, status}).then(response => {
      getList();
   });
}
// 手动执行
function handleExec(id) {
   dataDecodeExec({id}).then(response => {
      proxy.$modal.msgSuccess("执行成功，请在日志中查看执行进度");
   })
}

/** 提交按钮 */
function submitForm() {
   proxy.$refs["editRef"].validate(valid => {
      if (valid) {
         form.value.dataSystemId = props.systemId;
         if (editTargetId.value) {
            dataDecodeUpdate({...form.value, id: editTargetId.value}).then(response => {
               proxy.$modal.msgSuccess("修改成功");
               open.value = false;
               editTargetId.value = null;
               getList();
            });
            } else {
            dataDecodeAdd(form.value).then(response => {
               proxy.$modal.msgSuccess("新增成功");
               open.value = false;
               getList();
            });
         }
      }
   });
}

/** 删除按钮操作 */
function handleDelete(row) {
   proxy.$modal.confirm('是否确认删除名称为"' + row.name + '"的数据项?').then(function () {
      return dataDecodeDelete({ ids: row.id });
   }).then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
   }).catch(() => { });
}

const selectedList = ref([])
function handleSelectionChange(list) {
   selectedList.value = list
}

/** 多选删除操作 */
function handleDeleteBatch() {
   if (selectedList.value.length) {
      proxy.$modal.confirm('是否确认删除选中的' + selectedList.value.length + '个数据?').then(function () {
         const ids = selectedList.value.map(item => item.id).join(',');
         return dataDecodeDelete({ ids });
      }).then(() => {
         getList();
         proxy.$modal.msgSuccess("删除成功");
      }).catch(() => { });
   } else {
      proxy.$modal.msgError("请选择要删除的数据");
   }
}

const uploading = ref(false);
const fileUpload = ref(null)
const importFile = async (file) => {
   fileUpload.value.clearFiles()
   uploading.value = true;
   const formData = new FormData();
   formData.append("file", file.raw);
   const res = await axios.post(import.meta.env.VITE_APP_BASE_API + "/file/upload", formData, {
      headers: {
         "Content-Type": "multipart/form-data",
         Authorization: "Bearer " + getToken()
      },
   });

   if (res.data.code === 200) {
      proxy.$modal.msgSuccess('导入成功');
      form.value.fileUrl = res.data.data
   } else {
      proxy.$modal.msgError(res.data.msg);
   }
   uploading.value = false;
};
</script>
<style lang='scss' scoped>
   .app-container{
      padding-top: 0;
   }
</style>